<template>
  <view class="cardstyle" :style="{'background-color': bgColor}" @click="handleCardClick">
    <!-- 1. 带图新闻：图片左浮 + 标题右排 -->
    <view class="img-title-row" v-if="mode === 'news' && image">
      <image 
        :src="finalImage"
        @error="handlerImageError"
        class="news-img"
      ></image>
      <text class="news-title">{{ finalTitle }}</text>
    </view>
    <!-- 2. 无图新闻/置顶新闻：纯文字标题 -->
    <text :class="mode === 'ad' ? 'ad-title' : 'text-title'" v-else>{{ finalTitle }}</text>
    <!-- 3. 广告模块：多图横向排列 -->
    <view class="ad-box" v-if="mode === 'ad'">
      <image 
        v-for="(img, idx) in finalAdImages"
        :key="idx"
        :src="img"
        mode="aspectFill"
        class="ad-img"
        @error="handlerAdImageError(idx)"
      ></image>
    </view>
    
    <!-- 信息栏 + 点赞/分享/收藏按钮 -->
    <view class="tipsbox">
      <text v-if="isTop" class="top-tag">置顶</text>
      <text v-if="mode=='ad'" class=" ad-tag">广告</text>
      <text>{{ author }}</text>
      <text v-if="mode=='news'">{{ comments }}评</text>
      
      <view style="flex: 1; display: flex; justify-content: flex-end; align-items: center; gap: 15rpx;">
        <view class="time-wrap" v-if="mode !== 'ad'">
          <text>{{ time }}</text>
        </view>
        
        <!-- 点赞按钮（仅新闻显示） -->
        <view v-if="mode === 'news'" class="action-btn" @click.stop="handleLike">
          <uni-icons 
            type="heart" 
            :color="isLiked ? '#ff4444' : '#999'" 
            size="24"
          ></uni-icons>
        </view>
        
        <!-- 收藏按钮（仅新闻显示） -->
        <view v-if="mode === 'news'" class="action-btn" @click.stop="handleCollect">
          <uni-icons 
            type="star" 
            :color="isCollected ? '#ffd700' : '#999'" 
            size="24"
          ></uni-icons>
        </view>
        
        <!-- 分享按钮（仅新闻显示） -->
        <view v-if="mode === 'news'" class="action-btn" @click.stop="handleShare">
          <uni-icons 
            type="share" 
            color="#999" 
            size="24"
          ></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "cardViewText",
  props: {
    newsId: {
      type: [Number, String],
      required: true
    },
    image: {
      type: String,
      default: ""
    },
    bgColor: {
      type: String,
      default: "#fff"
    },
    mode: {
      type: String,
      default: "news",
      required: true
    },
    title: {
      type: String,
      default: "新闻标题",
      required: true
    },
    isTop: {
      type: Boolean,
      default: false,
      required: true
    },
    author: {
      type: String,
      default: "来源",
      required: true
    },
    comments: {
      type: Number,
      default: 0,
      required: true
    },
    time: {
      type: String,
      default: "2025.1.1",
      required: true
    },
    images: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultImage: "/static/load_default.png",
      failImage: "/static/load_fail.png",
      imageError: false,
      adImageErrors: [],
      isLiked: false,
      isCollected: false
    };
  },
  computed: {
    // 基础图片清洗
    showImage() {
      const safeImage = this.image ? this.image.replace(/<!--/g, '').replace(/-->/g, '') : "";
      return this.imageError ? this.failImage : (safeImage || this.defaultImage);
    },
    // 最终图片路径（二次清洗）
    finalImage() {
      return this.showImage.replace(/<!--/g, '').replace(/-->/g, '').trim();
    },
    // 基础标题清洗
    safeTitle() {
      return this.title.replace(/<!--/g, '').replace(/-->/g, '');
    },
    // 最终标题（二次清洗）
    finalTitle() {
      return this.safeTitle.replace(/<!--/g, '').replace(/-->/g, '').trim();
    },
    // 广告图片二次清洗
    finalAdImages() {
      if (!Array.isArray(this.images)) return [];
      return this.images.map(img => {
        return img.replace(/<!--/g, '').replace(/-->/g, '').trim();
      }).filter(img => img !== '');
    }
  },
  created() {
    this.initUserActionStatus()
  },
  methods: {
    // 卡片点击跳转（核心修复：传递正确的字符串ID）
    handleCardClick() {
      if (this.mode === 'ad') {
        // 广告跳转逻辑
        uni.navigateTo({
          url: this.jumpUrl || '/'
        });
        return;
      }
      // 新闻跳转：强制转为字符串ID，确保和详情页匹配
      uni.navigateTo({
        url: `/pages/news-detail/news-detail?id=${String(this.newsId)}`
      });
    },
    
    // 初始化点赞/收藏状态
    initUserActionStatus() {
      const app = getApp()
      if (!app || !this.newsId) return;
      this.isLiked = app.isLiked ? app.isLiked(String(this.newsId)) : false;
      this.isCollected = app.isCollected ? app.isCollected(String(this.newsId)) : false;
    },
    
    // 处理图片加载错误
    handlerImageError() {
      this.imageError = true;
    },
    handlerAdImageError(idx) {
      this.$set(this.adImageErrors, idx, true);
    },
    
    // 点赞/取消点赞
    handleLike() {
      const app = getApp()
      if (!app || !this.newsId) return;
      const newsIdStr = String(this.newsId);
      
      if (this.isLiked) {
        app.cancelLike?.(newsIdStr)
      } else {
        app.likeNews?.(newsIdStr)
      }
      this.isLiked = !this.isLiked
    },
    
    // 收藏/取消收藏
    handleCollect() {
      const app = getApp()
      if (!app || !this.newsId) return;
      const newsIdStr = String(this.newsId);
      
      if (this.isCollected) {
        app.cancelCollect?.(newsIdStr)
      } else {
        app.collectNews?.(newsIdStr)
      }
      this.isCollected = !this.isCollected
    },
    
    // 分享新闻
    handleShare() {
      const app = getApp()
      if (!app || !this.newsId) return;
      app.shareNews?.(String(this.newsId))
    }
  }
};
</script>

<style scoped>
.cardstyle {
  border-radius: 10px;
  padding: 15rpx;
  margin-bottom: 10rpx;
  position: relative;
  cursor: pointer;
}
.img-title-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8rpx;
}
.news-img {
  width: 120rpx;
  height: 90rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
}
.news-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  line-height: 44rpx;
}
.text-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  line-height: 44rpx;
}
.ad-title {
  display: block;
  font-size: 32rpx;
  font-weight: normal;
  margin-bottom: 8rpx;
  line-height: 44rpx;
  color: #999;
}
.ad-box {
  display: flex;
  gap: 10rpx;
  margin-bottom: 8rpx; 
}
.ad-img {
  flex: 1;
  height: 120rpx;
  border-radius: 6rpx;
}
.tipsbox {
  display: flex;
  gap: 16rpx;
  font-size: 28rpx;
  color: #999;
  flex-wrap: wrap;
  align-items: center;
}
.top-tag {
  color: #f00;
  font-weight: bold;
}
.ad-tag {
  color: #66b1ff; 
  font-weight: bold;
}
.author {
  flex: 1;
}
.time-wrap {
  white-space: nowrap;
}
.action-btn {
  padding: 5rpx;
  cursor: pointer;
}
</style>